package com.example.shuiyin.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class ApiMonitorAspect {

    @Pointcut("execution(* com.example.shuiyin.controller.*.*(..))")
    public void controllerMethods() {}

    @Around("controllerMethods()")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        
        // 获取请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        
        // 记录请求信息
        log.info("请求URL: {}", request.getRequestURL().toString());
        log.info("请求方法: {}", request.getMethod());
        log.info("请求IP: {}", request.getRemoteAddr());
        log.info("调用方法: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        log.info("参数: {}", Arrays.toString(joinPoint.getArgs()));
        
        // 执行方法
        Object result = joinPoint.proceed();
        
        // 计算执行时间
        long executionTime = System.currentTimeMillis() - startTime;
        
        // 记录执行时间
        log.info("方法执行时间: {} ms", executionTime);
        
        if (executionTime > 1000) {
            log.warn("方法执行时间超过1秒，需要优化: {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        }
        
        return result;
    }
} 